package com.lanlian.cayman.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.utils.NumberManager;
import com.lanlian.cayman.utils.SimpleTextWatcher;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.MyEditText;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PositionDetailsInfo;
import com.lanlian.commonlib.bean.ProfitLossInfo;
import com.lanlian.commonlib.bean.ReqDeleteProfitLoss;
import com.lanlian.commonlib.bean.ReqSetProfitLoss;
import com.lanlian.commonlib.bean.ReqUpdateProfitLoss;
import com.lanlian.commonlib.data.GoodsBean;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.utillib.MoneyTextWatcher;
import com.lanlian.utillib.NumberUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

import static java.math.BigDecimal.ROUND_HALF_UP;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/23 20:56
 *     desc   : 设置止盈止损
 *     version: 1.0
 * </pre>
 */
public class ProfitLossSetupActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTvContractName;
    private TextView mTvDirection;
    private TextView mTvPrice;
    private TextView mTvOpenPrice;
    private MyEditText mEtProfitPrice;
    private MyEditText mEtProfitMoney;
    private LinearLayout mLaySeniorProfit;
    private MyEditText mEtProfitBackPrice;
    private MyEditText mEtProfitBackMoney;
    private MyEditText mEtLossPrice;
    private MyEditText mEtLossMoney;
    private LinearLayout mLaySeniorLoss;
    private MyEditText mEtLossBackPrice;
    private MyEditText mEtLossBackMoney;
    private EditText mEtAmount;
    private RadioGroup mRgDirection;
    private TextView mTvSave;
    private TextView mTvDelete;
    private RelativeLayout mLayProfitWeituoPrice;
    private MyEditText mEtProfitWeituoPrice;
    private RelativeLayout mLayProfitBackWeituoPrice;
    private MyEditText mEtProfitBackWeituoPrice;
    private RelativeLayout mLayLossWeituoPrice;
    private MyEditText mEtLossWeituoPrice;
    private RelativeLayout mLayLossBackWeituoPrice;
    private MyEditText mEtLossBackWeituoPrice;
    private TextView mTvPositionNum;

    private boolean mIsNew;
    private boolean mIsOrdinary;

    private PositionDetailsInfo mPositionDetailsInfo;
    private ProfitLossInfo mProfitLossInfo;
    private int mOrderType = 1;
    private double mCurrentPrice;
    private GoodsBean mGoodsBean;
    private String minChange;
    private String priceUnit;

    private Double profitPrice;
    private Double lossPrice;
    private Double profitMoney;
    private Double lossMoney;
    private Double profitBackPrice;
    private Double lossBackPrice;
    private Double profitBackMoney;
    private Double lossBackMoney;
    private Double profitWeituoPrice;
    private Double profitBackWeituoPrice;
    private Double lossWeituoPrice;
    private Double lossBackWeituoPrice;
    private int num;
    private int count;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profit_loss_setup, true);
        initData();
        initView();
        setPositionDetailsInfo();
        setProfitInfo();
        setListeners();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("设置止盈止损");
        setRightImage(R.mipmap.documentary_icon_problem);
        mTvContractName = findViewById(R.id.tv_contract_name);
        mTvDirection = findViewById(R.id.tv_direction);
        mTvPrice = findViewById(R.id.tv_price);
        mEtProfitPrice = findViewById(R.id.et_profit_price);
        mEtProfitMoney = findViewById(R.id.et_profit_money);
        mLaySeniorProfit = findViewById(R.id.lay_senior_profit);
        mEtProfitBackPrice = findViewById(R.id.et_profit_back_price);
        mEtProfitBackMoney = findViewById(R.id.et_profit_back_money);
        mEtLossPrice = findViewById(R.id.et_loss_price);
        mEtLossMoney = findViewById(R.id.et_loss_money);
        mLaySeniorLoss = findViewById(R.id.lay_senior_loss);
        mEtLossBackPrice = findViewById(R.id.et_loss_back_price);
        mEtLossBackMoney = findViewById(R.id.et_loss_back_money);
        mEtAmount = findViewById(R.id.et_amount);
        mRgDirection = findViewById(R.id.rg_direction);
        mTvSave = findViewById(R.id.tv_save);
        mTvDelete = findViewById(R.id.tv_delete);
        mTvOpenPrice = findViewById(R.id.tv_open_price);
        mLayProfitWeituoPrice = findViewById(R.id.lay_profit_weituo_price);
        mEtProfitWeituoPrice = findViewById(R.id.et_profit_weituo_price);
        mLayProfitBackWeituoPrice = findViewById(R.id.lay_profit_back_weituo_price);
        mEtProfitBackWeituoPrice = findViewById(R.id.et_profit_back_weituo_price);
        mLayLossWeituoPrice = findViewById(R.id.lay_loss_weituo_price);
        mEtLossWeituoPrice = findViewById(R.id.et_loss_weituo_price);
        mLayLossBackWeituoPrice = findViewById(R.id.lay_loss_back_weituo_price);
        mEtLossBackWeituoPrice = findViewById(R.id.et_loss_back_weituo_price);
        mTvPositionNum = findViewById(R.id.tv_position_num);

        mTvDelete.setVisibility(mIsNew ? View.GONE : View.VISIBLE);
        mLaySeniorProfit.setVisibility(mIsOrdinary ? View.GONE : View.VISIBLE);
        mLaySeniorLoss.setVisibility(mIsOrdinary ? View.GONE : View.VISIBLE);

        setEditable(mEtProfitWeituoPrice, false);
        setEditable(mEtProfitBackWeituoPrice, false);
        setEditable(mEtLossWeituoPrice, false);
        setEditable(mEtLossBackWeituoPrice, false);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvSave.setOnClickListener(this);
        mTvDelete.setOnClickListener(this);
        mImgAction.setOnClickListener(this);
        mEtProfitWeituoPrice.addTextChangedListener(new MoneyTextWatcher(mEtProfitWeituoPrice).setDigits(count));
        mEtProfitBackWeituoPrice.addTextChangedListener(new MoneyTextWatcher(mEtProfitBackWeituoPrice).setDigits(count));
        mEtLossWeituoPrice.addTextChangedListener(new MoneyTextWatcher(mEtLossWeituoPrice).setDigits(count));
        mEtLossBackWeituoPrice.addTextChangedListener(new MoneyTextWatcher(mEtLossBackWeituoPrice).setDigits(count));
        mRgDirection.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_forward:
                        mOrderType = 1;
                        mLayProfitWeituoPrice.setVisibility(View.GONE);
                        mLayProfitBackWeituoPrice.setVisibility(View.GONE);
                        mLayLossWeituoPrice.setVisibility(View.GONE);
                        mLayLossBackWeituoPrice.setVisibility(View.GONE);
                        break;
                    case R.id.rb_reverse:
                        mOrderType = 2;
                        mLayProfitWeituoPrice.setVisibility(View.VISIBLE);
                        mLayProfitBackWeituoPrice.setVisibility(mIsOrdinary ? View.GONE : View.VISIBLE);
                        mLayLossWeituoPrice.setVisibility(View.VISIBLE);
                        mLayLossBackWeituoPrice.setVisibility(mIsOrdinary ? View.GONE : View.VISIBLE);
                        break;
                    default:
                        break;
                }
            }
        });
        mEtProfitPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtProfitPrice.addTextChangedListener(new MoneyTextWatcher(mEtProfitPrice).setDigits(count));
                    mEtProfitPrice.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtProfitWeituoPrice, true);
                                double price = new BigDecimal(s.toString()).setScale(count, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtProfitMoney.setText(calculationPnl(price).toPlainString());
                            } else {
                                mEtProfitWeituoPrice.setText("");
                                setEditable(mEtProfitWeituoPrice, false);
                                mEtProfitMoney.setText("");
                            }
                        }
                    });
                } else {
                    mEtProfitPrice.clearTextChangedListeners();
                }
            }
        });
        mEtProfitMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtProfitMoney.addTextChangedListener(new MoneyTextWatcher(mEtProfitMoney));
                    mEtProfitMoney.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtProfitWeituoPrice, true);
                                double pnl = new BigDecimal(s.toString()).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtProfitPrice.setText(calculationPrice(pnl).toPlainString());
                            } else {
                                mEtProfitWeituoPrice.setText("");
                                setEditable(mEtProfitWeituoPrice, false);
                                mEtProfitPrice.setText("");
                            }
                        }
                    });
                } else {
                    mEtProfitMoney.clearTextChangedListeners();
                }
            }
        });

        mEtLossPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtLossPrice.addTextChangedListener(new MoneyTextWatcher(mEtLossPrice).setDigits(count));
                    mEtLossPrice.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtLossWeituoPrice, true);
                                double price = new BigDecimal(s.toString()).setScale(count, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtLossMoney.setText(calculationPnl(price).multiply(new BigDecimal("-1")).toPlainString());
                            } else {
                                mEtLossWeituoPrice.setText("");
                                setEditable(mEtLossWeituoPrice, false);
                                mEtLossMoney.setText("");
                            }
                        }
                    });
                } else {
                    mEtLossPrice.clearTextChangedListeners();
                }
            }
        });
        mEtLossMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtLossMoney.addTextChangedListener(new MoneyTextWatcher(mEtLossMoney));
                    mEtLossMoney.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtLossWeituoPrice, true);
                                double pnl = new BigDecimal(s.toString()).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtLossPrice.setText(calculationPrice(-pnl).toPlainString());
                            } else {
                                mEtLossWeituoPrice.setText("");
                                setEditable(mEtLossWeituoPrice, false);
                                mEtLossPrice.setText("");
                            }
                        }
                    });
                } else {
                    mEtLossMoney.clearTextChangedListeners();
                }
            }
        });

        mEtProfitBackPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtProfitBackPrice.addTextChangedListener(new MoneyTextWatcher(mEtProfitBackPrice).setDigits(count));
                    mEtProfitBackPrice.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtProfitBackWeituoPrice, true);
                                double price = new BigDecimal(s.toString()).setScale(count + 1, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtProfitBackMoney.setText(calculationPnl(price).toPlainString());
                            } else {
                                mEtProfitBackWeituoPrice.setText("");
                                setEditable(mEtProfitBackWeituoPrice, false);
                                mEtProfitBackMoney.setText("");
                            }
                        }
                    });
                } else {
                    mEtProfitBackPrice.clearTextChangedListeners();
                }
            }
        });
        mEtProfitBackMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtProfitBackMoney.addTextChangedListener(new MoneyTextWatcher(mEtProfitBackMoney));
                    mEtProfitBackMoney.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtProfitBackWeituoPrice, true);
                                double pnl = new BigDecimal(s.toString()).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtProfitBackPrice.setText(calculationPrice(pnl).toPlainString());
                            } else {
                                mEtProfitBackWeituoPrice.setText("");
                                setEditable(mEtProfitBackWeituoPrice, false);
                                mEtProfitBackPrice.setText("");
                            }
                        }
                    });
                } else {
                    mEtProfitBackMoney.clearTextChangedListeners();
                }
            }
        });

        mEtLossBackPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtLossBackPrice.addTextChangedListener(new MoneyTextWatcher(mEtLossBackPrice).setDigits(count));
                    mEtLossBackPrice.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtLossBackWeituoPrice, true);
                                double price = new BigDecimal(s.toString()).setScale(count, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtLossBackMoney.setText(calculationPnl(price).multiply(new BigDecimal("-1")).toPlainString());
                            } else {
                                mEtLossBackWeituoPrice.setText("");
                                setEditable(mEtLossBackWeituoPrice, false);
                                mEtLossBackMoney.setText("");
                            }
                        }
                    });
                } else {
                    mEtLossBackPrice.clearTextChangedListeners();
                }
            }
        });
        mEtLossBackMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mEtLossBackMoney.addTextChangedListener(new MoneyTextWatcher(mEtLossBackMoney));
                    mEtLossBackMoney.addTextChangedListener(new SimpleTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable s) {
                            if (!TextUtils.isEmpty(s.toString()) && !"-".equals(s.toString())
                                    && !".".equals(s.toString())) {
                                setEditable(mEtLossBackWeituoPrice, true);
                                double pnl = new BigDecimal(s.toString()).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                                mEtLossBackPrice.setText(calculationPrice(-pnl).toPlainString());
                            } else {
                                mEtLossBackWeituoPrice.setText("");
                                setEditable(mEtLossBackWeituoPrice, false);
                                mEtLossBackPrice.setText("");
                            }
                        }
                    });
                } else {
                    mEtLossBackMoney.clearTextChangedListeners();
                }
            }
        });
        mEtAmount.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if ("0".equals(s.toString())) {
                    mEtAmount.setText("1");
                    mEtAmount.setSelection(1);
                    return;
                }
                Double profitPrice = TextUtils.isEmpty(mEtProfitPrice.getText().toString()) ? null : Double.valueOf(mEtProfitPrice.getText().toString());
                Double lossPrice = TextUtils.isEmpty(mEtLossPrice.getText().toString()) ? null : Double.valueOf(mEtLossPrice.getText().toString());
                Double profitBackPrice = TextUtils.isEmpty(mEtProfitBackPrice.getText().toString()) ? null : Double.valueOf(mEtProfitBackPrice.getText().toString());
                Double lossBackPrice = TextUtils.isEmpty(mEtLossBackPrice.getText().toString()) ? null : Double.valueOf(mEtLossBackPrice.getText().toString());
                if (profitPrice != null) {
                    mEtProfitMoney.setText(calculationPnl(profitPrice).toPlainString());
                }
                if (lossPrice != null) {
                    mEtLossMoney.setText(calculationPnl(lossPrice).multiply(new BigDecimal("-1")).toPlainString());
                }
                if (profitBackPrice != null) {
                    mEtProfitBackMoney.setText(calculationPnl(profitBackPrice).toPlainString());
                }
                if (lossBackPrice != null) {
                    mEtLossBackMoney.setText(calculationPnl(lossBackPrice).multiply(new BigDecimal("-1")).toPlainString());
                }
            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
        mIsNew = getIntent().getBooleanExtra("isNew", false);
        mIsOrdinary = getIntent().getBooleanExtra("isOrdinary", false);
        mPositionDetailsInfo = (PositionDetailsInfo) getIntent().getSerializableExtra("positionDetailsInfo");
        mProfitLossInfo = (ProfitLossInfo) getIntent().getSerializableExtra("profitLossInfo");
        mGoodsBean = MarketFragment.getRespMarket().getGoods(mPositionDetailsInfo.getVcContractCode());
        if (mGoodsBean != null) {
            minChange = mGoodsBean.minChange;
            priceUnit = mGoodsBean.priceUnit;
            count = NumberManager.getNumberDecimalDigits(mGoodsBean.minChange);
        }
    }

    private void setPositionDetailsInfo() {
        mTvContractName.setText(mPositionDetailsInfo.getContractName());
        mTvDirection.setText("1".equals(mPositionDetailsInfo.getcPositionFlag()) ? "买" : "卖");
        if ("1".equals(mPositionDetailsInfo.getcPositionFlag())) {
            mTvDirection.setTextColor(getResources().getColor(R.color.color_T7));
        } else {
            mTvDirection.setTextColor(getResources().getColor(R.color.color_T8));
        }
        String averagePrice = NumberUtils.roundStr(mPositionDetailsInfo.getJj(), count + 1, BigDecimal.ROUND_HALF_UP);
        mTvOpenPrice.setText(averagePrice);
        mTvPrice.setText(mPositionDetailsInfo.getCurrentPrice());
        mTvPositionNum.setText(String.valueOf(mPositionDetailsInfo.getlCurrentAmount()));
    }

    private void setProfitInfo() {
        if (mProfitLossInfo != null) {
            mOrderType = mProfitLossInfo.getOrderType();
            if (mProfitLossInfo.getPriceZy() != null) {
                setEditable(mEtProfitWeituoPrice, true);
                mEtProfitPrice.setText(mProfitLossInfo.getPriceZy().toPlainString());
            } else {
                setEditable(mEtProfitWeituoPrice, false);
            }
            if (mProfitLossInfo.getStopProfit() != null) {
                mEtProfitMoney.setText(mProfitLossInfo.getStopProfit().toPlainString());
            }
            if (mProfitLossInfo.getPriceZs() != null) {
                setEditable(mEtLossWeituoPrice, true);
                mEtLossPrice.setText(mProfitLossInfo.getPriceZs().toPlainString());
            } else {
                setEditable(mEtLossWeituoPrice, false);
            }
            if (mProfitLossInfo.getStopLoss() != null) {
                mEtLossMoney.setText(mProfitLossInfo.getStopLoss().toPlainString());
            }
            mEtAmount.setText(mProfitLossInfo.getNum().toString());
            mRgDirection.check(mProfitLossInfo.getOrderType() == 1 ? R.id.rb_forward : R.id.rb_reverse);
            if (!mIsOrdinary) {
                if (mProfitLossInfo.getPriceZyRt() != null) {
                    setEditable(mEtProfitBackWeituoPrice, true);
                    mEtProfitBackPrice.setText(mProfitLossInfo.getPriceZyRt().toPlainString());
                } else {
                    setEditable(mEtProfitBackWeituoPrice, false);
                }
                if (mProfitLossInfo.getStopProfitRt() != null) {
                    mEtProfitBackMoney.setText(mProfitLossInfo.getStopProfitRt().toPlainString());
                }
                if (mProfitLossInfo.getPriceZsRt() != null) {
                    setEditable(mEtLossBackWeituoPrice, true);
                    mEtLossBackPrice.setText(mProfitLossInfo.getPriceZsRt().toPlainString());
                } else {
                    setEditable(mEtLossBackWeituoPrice, false);
                }
                if (mProfitLossInfo.getStopLossRt() != null) {
                    mEtLossBackMoney.setText(mProfitLossInfo.getStopLossRt().toPlainString());
                }
            }
            if (mProfitLossInfo.getOrderType() == 2) {
                if (mProfitLossInfo.getLimitPriceZy() != null) {
                    mEtProfitWeituoPrice.setText(mProfitLossInfo.getLimitPriceZy().toPlainString());
                }
                if (mProfitLossInfo.getLimitPriceZs() != null) {
                    mEtLossWeituoPrice.setText(mProfitLossInfo.getLimitPriceZs().toPlainString());
                }
                if (mProfitLossInfo.getLimitPriceZyrt() != null) {
                    mEtProfitBackWeituoPrice.setText(mProfitLossInfo.getLimitPriceZyrt().toPlainString());
                }
                if (mProfitLossInfo.getLimitPriceZsrt() != null) {
                    mEtLossBackWeituoPrice.setText(mProfitLossInfo.getLimitPriceZsrt().toPlainString());
                }
                mLayProfitWeituoPrice.setVisibility(View.VISIBLE);
                mLayProfitBackWeituoPrice.setVisibility(mIsOrdinary ? View.GONE : View.VISIBLE);
                mLayLossWeituoPrice.setVisibility(View.VISIBLE);
                mLayLossBackWeituoPrice.setVisibility(mIsOrdinary ? View.GONE : View.VISIBLE);
            } else {
                mLayProfitWeituoPrice.setVisibility(View.GONE);
                mLayProfitBackWeituoPrice.setVisibility(View.GONE);
                mLayLossWeituoPrice.setVisibility(View.GONE);
                mLayLossBackWeituoPrice.setVisibility(View.GONE);
            }
        }
    }

    private void setEditable(EditText editText, boolean editable) {
        editText.setFocusableInTouchMode(editable);
        editText.setFocusable(editable);
    }

    private BigDecimal calculationPnl(double price) {
        String num = TextUtils.isEmpty(mEtAmount.getText().toString()) ? "0" : mEtAmount.getText().toString();
        String flag = "1".equals(mPositionDetailsInfo.getcPositionFlag()) ? "1" : "-1";
        BigDecimal pnl = new BigDecimal(String.valueOf(price)).subtract(new BigDecimal(String.valueOf(mPositionDetailsInfo.getJj())))
                .multiply(new BigDecimal(priceUnit))
                .multiply(new BigDecimal(flag)).multiply(new BigDecimal(num))
                .divide(new BigDecimal(minChange), 2, RoundingMode.DOWN);
        return pnl.setScale(2, RoundingMode.DOWN);
    }

    private BigDecimal calculationPrice(double pnl) {
        String num = TextUtils.isEmpty(mEtAmount.getText().toString()) ? "0" : mEtAmount.getText().toString();
        String flag = "1".equals(mPositionDetailsInfo.getcPositionFlag()) ? "1" : "-1";
        if ("0".equals(num)) {
            return new BigDecimal("0").setScale(count, RoundingMode.DOWN);
        }
        double price = new BigDecimal(String.valueOf(pnl)).divide(new BigDecimal(flag))
                .multiply(new BigDecimal(minChange)).divide(new BigDecimal(num), count + 1, RoundingMode.DOWN)
                .divide(new BigDecimal(priceUnit), count + 1, RoundingMode.DOWN)
                .doubleValue() + mPositionDetailsInfo.getJj();
        return new BigDecimal(String.valueOf(price)).setScale(count, RoundingMode.DOWN);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_delete:
                ReqDeleteProfitLoss reqDeleteProfitLoss = new ReqDeleteProfitLoss();
                reqDeleteProfitLoss.setHoldingId(mPositionDetailsInfo.getlPositionNo());
                reqDeleteProfitLoss.setZyzsId(mProfitLossInfo.getId());
                reqDeleteProfitLoss.setStatus(2);
                reqDeleteProfitLoss.setPlate("APP");
                showLoadingDialog();
                VolleyRequestUtils.getInstance().deleteProfitLoss(this.toString(), reqDeleteProfitLoss,
                        new INetWorkCallback() {
                            @Override
                            public void onSuccess(Object response) {
                                EventBusUtils.post(new EventMessage(EventCode.EVENT_PROFITLOSS_REFRESH));
                                dismissLoadingDialog();
                                showToast("删除成功");
                                finish();
                            }

                            @Override
                            public void onFail(BaseResponse baseResponse) {
                                dismissLoadingDialog();
                                showToast(baseResponse.getMsg());
                            }
                        });
                break;
            case R.id.tv_save:
                //买：止盈价>最新价>止盈回撤价>开仓价>止损回撤价>最新价>止损价  如果是行情向上只能设置止盈 否则设置止损
                //卖：止盈价<最新价<止盈回撤价<开仓价<止损回撤价<最新价<止损价  如果是行情向上只能设置止损 否则设置止盈
                profitPrice = TextUtils.isEmpty(mEtProfitPrice.getText().toString()) ? null : Double.valueOf(mEtProfitPrice.getText().toString());
                lossPrice = TextUtils.isEmpty(mEtLossPrice.getText().toString()) ? null : Double.valueOf(mEtLossPrice.getText().toString());
                profitMoney = TextUtils.isEmpty(mEtProfitMoney.getText().toString()) ? null : Double.valueOf(mEtProfitMoney.getText().toString());
                lossMoney = TextUtils.isEmpty(mEtLossMoney.getText().toString()) ? null : Double.valueOf(mEtLossMoney.getText().toString());
                profitBackPrice = TextUtils.isEmpty(mEtProfitBackPrice.getText().toString()) ? null : Double.valueOf(mEtProfitBackPrice.getText().toString());
                lossBackPrice = TextUtils.isEmpty(mEtLossBackPrice.getText().toString()) ? null : Double.valueOf(mEtLossBackPrice.getText().toString());
                profitBackMoney = TextUtils.isEmpty(mEtProfitBackMoney.getText().toString()) ? null : Double.valueOf(mEtProfitBackMoney.getText().toString());
                lossBackMoney = TextUtils.isEmpty(mEtLossBackMoney.getText().toString()) ? null : Double.valueOf(mEtLossBackMoney.getText().toString());
                profitWeituoPrice = TextUtils.isEmpty(mEtProfitWeituoPrice.getText().toString()) ?
                        null : Double.valueOf(mEtProfitWeituoPrice.getText().toString());
                profitBackWeituoPrice = TextUtils.isEmpty(mEtProfitBackWeituoPrice.getText().toString()) ?
                        null : Double.valueOf(mEtProfitBackWeituoPrice.getText().toString());
                lossWeituoPrice = TextUtils.isEmpty(mEtLossWeituoPrice.getText().toString()) ?
                        null : Double.valueOf(mEtLossWeituoPrice.getText().toString());
                lossBackWeituoPrice = TextUtils.isEmpty(mEtLossBackWeituoPrice.getText().toString()) ?
                        null : Double.valueOf(mEtLossBackWeituoPrice.getText().toString());
                num = TextUtils.isEmpty(mEtAmount.getText().toString()) ? 0 : Integer.valueOf(mEtAmount.getText().toString());
                if (num == 0) {
                    showToast("请设置手数");
                    return;
                }
                if (lossPrice == null && profitPrice == null && lossBackPrice == null && profitBackPrice == null) {
                    if (mIsOrdinary) {
                        showToast("止盈/止损至少设置一项");
                    } else {
                        showToast("止盈/止损/止盈回撤/止损回撤至少设置一项");
                    }
                    return;
                }
                if (!ordinaryJudge()) {
                    return;
                }
                if (!mIsOrdinary) {
                    if (!seniorJudge()) {
                        return;
                    }
                }
                if (mOrderType == 2) {
                    if (profitPrice != null && profitWeituoPrice == null) {
                        showToast("请设置止盈委托价");
                        return;
                    }
                    if (lossPrice != null && lossWeituoPrice == null) {
                        showToast("请设置止损委托价");
                        return;
                    }
                    if (profitBackPrice != null && profitBackWeituoPrice == null) {
                        showToast("请设置止盈回撤委托价");
                        return;
                    }
                    if (lossBackPrice != null && lossBackWeituoPrice == null) {
                        showToast("请设置止损回撤委托价");
                        return;
                    }
                }
                if (num > ProfitLossActivity.mAmount) {
                    showToast("可设置手数超出限制");
                    return;
                }
                if (mProfitLossInfo != null) {
                    updateProfitLoss();
                } else {
                    addProfitLoss();
                }
                break;
            case R.id.img_action:
                OnEventUtils.onEvent(this, OnEventID.STOP_PNL_IMAGE);
                startActivity(new Intent(this, ProfitLossImageActivity.class));
                break;
            default:
                break;
        }
    }

    /**
     * 普通止盈止损设置判断
     */
    private boolean ordinaryJudge() {
        if (profitPrice != null && profitPrice == 0) {
            showToast("止盈价格不能为0");
            return false;
        }
        if (lossPrice != null && lossPrice == 0) {
            showToast("止损价格不能为0");
            return false;
        }
        if ("1".equals(mPositionDetailsInfo.getcPositionFlag())) {
            if (profitPrice != null && profitPrice < mPositionDetailsInfo.getJj()) {
                showToast("止盈价格必须大于开仓价");
                return false;
            }
            if (lossPrice != null && lossPrice > mPositionDetailsInfo.getJj()) {
                showToast("止损价格必须小于开仓价");
                return false;
            }
            if (mOrderType == 2) {
                if (profitWeituoPrice != null && profitPrice != null
                        && profitWeituoPrice > profitPrice) {
                    showToast("止盈委托价必须小于止盈价格");
                    return false;
                }
                if (profitWeituoPrice != null && profitPrice != null
                        && profitWeituoPrice < mPositionDetailsInfo.getJj()) {
                    showToast("止盈委托价必须大于开仓价");
                    return false;
                }
                if (lossWeituoPrice != null && lossPrice != null
                        && lossWeituoPrice > lossPrice) {
                    showToast("止损委托价必须小于止损价格");
                    return false;
                }
            }
        } else {
            if (profitPrice != null && profitPrice > mPositionDetailsInfo.getJj()) {
                showToast("止盈价格必须小于开仓价");
                return false;
            }
            if (lossPrice != null && lossPrice < mPositionDetailsInfo.getJj()) {
                showToast("止损价格必须大于开仓价");
                return false;
            }
            if (mOrderType == 2) {
                if (profitWeituoPrice != null && profitPrice != null
                        && profitWeituoPrice < profitPrice) {
                    showToast("止盈委托价必须大于止盈价格");
                    return false;
                }
                if (profitWeituoPrice != null && profitPrice != null
                        && profitWeituoPrice > mPositionDetailsInfo.getJj()) {
                    showToast("止盈委托价必须小于开仓价");
                    return false;
                }
                if (lossWeituoPrice != null && lossPrice != null
                        && lossWeituoPrice < lossPrice) {
                    showToast("止损委托价必须大于止损价格");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 高级止盈止损判断
     */
    private boolean seniorJudge() {
        if (profitBackPrice != null && profitBackPrice == 0) {
            showToast("止盈回撤价格不能为0");
            return false;
        }
        if (lossBackPrice != null && lossBackPrice == 0) {
            showToast("止损回撤价格不能为0");
            return false;
        }
        if ("1".equals(mPositionDetailsInfo.getcPositionFlag())) {
            if (mCurrentPrice > mPositionDetailsInfo.getJj()) {
                if (profitPrice != null && profitPrice < mCurrentPrice) {
                    showToast("止盈价格必须大于当前最新价");
                    return false;
                }
                if (profitBackPrice != null && profitBackPrice > mCurrentPrice) {
                    showToast("止盈回撤价格必须小于当前最新价");
                    return false;
                }
                if (profitBackPrice != null && profitBackPrice < mPositionDetailsInfo.getJj()) {
                    showToast("止盈回撤价格必须大于开仓价");
                    return false;
                }
                if (lossBackPrice != null) {
                    showToast("盈利中，不能设置止损回撤价");
                    return false;
                }
            } else {
                if (lossPrice != null && lossPrice > mCurrentPrice) {
                    showToast("止损价格必须小于当前最新价");
                    return false;
                }
                if (lossBackPrice != null && lossBackPrice < mCurrentPrice) {
                    showToast("止损回撤价格必须大于当前最新价");
                    return false;
                }
                if (lossBackPrice != null && lossBackPrice > mPositionDetailsInfo.getJj()) {
                    showToast("止损回撤价格必须小于开仓价");
                    return false;
                }
                if (profitBackPrice != null) {
                    showToast("亏损中，不能设置止盈回撤价");
                    return false;
                }
            }
            if (mOrderType == 2) {
                if (profitBackWeituoPrice != null && profitBackPrice != null
                        && profitBackWeituoPrice > profitBackPrice) {
                    showToast("止盈回撤委托价必须小于止盈回撤价");
                    return false;
                }
                if (profitBackWeituoPrice != null && profitBackPrice != null
                        && profitBackWeituoPrice < mPositionDetailsInfo.getJj()) {
                    showToast("止盈回撤委托价必须大于开仓价");
                    return false;
                }
                if (lossBackWeituoPrice != null && lossBackPrice != null
                        && lossBackWeituoPrice > lossBackPrice) {
                    showToast("止损回撤委托价必须小于止损回撤价");
                    return false;
                }
            }
        } else {
            if (mCurrentPrice < mPositionDetailsInfo.getJj()) {
                if (profitPrice != null && profitPrice > mCurrentPrice) {
                    showToast("止盈价格必须小于当前最新价");
                    return false;
                }
                if (profitBackPrice != null && profitBackPrice < mCurrentPrice) {
                    showToast("止盈回撤价格必须大于当前最新价");
                    return false;
                }
                if (profitBackPrice != null && profitBackPrice > mPositionDetailsInfo.getJj()) {
                    showToast("止盈回撤价格必须小于开仓价");
                    return false;
                }
                if (lossBackPrice != null) {
                    showToast("盈利中，不能设置止损回撤价");
                    return false;
                }
            } else {
                if (lossPrice != null && lossPrice < mCurrentPrice) {
                    showToast("止损价格必须大于当前最新价");
                    return false;
                }
                if (lossBackPrice != null && lossBackPrice > mCurrentPrice) {
                    showToast("止损回撤价格必须小于当前最新价");
                    return false;
                }
                if (lossBackPrice != null && lossBackPrice < mPositionDetailsInfo.getJj()) {
                    showToast("止损回撤价格必须大于当前开仓价");
                    return false;
                }
                if (profitBackPrice != null) {
                    showToast("亏损中，不能设置止盈回撤价");
                    return false;
                }
            }
            if (mOrderType == 2) {
                if (profitBackWeituoPrice != null && profitBackPrice != null
                        && profitBackWeituoPrice < profitBackPrice) {
                    showToast("止盈回撤委托价必须大于止盈回撤价");
                    return false;
                }
                if (profitBackWeituoPrice != null && profitBackPrice != null
                        && profitBackWeituoPrice > mPositionDetailsInfo.getJj()) {
                    showToast("止盈回撤委托价必须小于开仓价");
                    return false;
                }
                if (lossBackWeituoPrice != null && lossBackPrice != null
                        && lossBackWeituoPrice < lossBackPrice) {
                    showToast("止损回撤委托价必须大于止损回撤价");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 新增止盈止损
     */
    private void addProfitLoss() {
        ReqSetProfitLoss reqSetProfitLoss = new ReqSetProfitLoss();
        reqSetProfitLoss.setHoldingId(mPositionDetailsInfo.getlPositionNo());
        reqSetProfitLoss.setNum(num);
        reqSetProfitLoss.setOrderType(mOrderType);
        reqSetProfitLoss.setPlate("APP");
        reqSetProfitLoss.setPriceZy(profitPrice);
        reqSetProfitLoss.setStopProfit(profitMoney);
        reqSetProfitLoss.setPriceZs(lossPrice);
        reqSetProfitLoss.setStopLoss(lossMoney);
        if (!mIsOrdinary) {
            reqSetProfitLoss.setPriceZyRt(profitBackPrice);
            reqSetProfitLoss.setStopProfitRt(profitBackMoney);
            reqSetProfitLoss.setPriceZsRt(lossBackPrice);
            reqSetProfitLoss.setStopLossRt(lossBackMoney);
        }
        if (mOrderType == 2) {
            reqSetProfitLoss.setLimitPriceZy(profitWeituoPrice);
            reqSetProfitLoss.setLimitPriceZs(lossWeituoPrice);
            reqSetProfitLoss.setLimitPriceZyrt(profitBackWeituoPrice);
            reqSetProfitLoss.setLimitPriceZsrt(lossBackWeituoPrice);
        }
        mTvSave.setClickable(false);
        showLoadingDialog();
        VolleyRequestUtils.getInstance().setProfitLoss(this.toString(), reqSetProfitLoss, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                EventBusUtils.post(new EventMessage(EventCode.EVENT_PROFITLOSS_REFRESH));
                dismissLoadingDialog();
                showToast("设置成功");
                finish();
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
                mTvSave.setClickable(true);
                dismissLoadingDialog();
                showToast(baseResponse.getMsg());
            }
        });
    }

    /**
     * 修改止盈止损
     */
    private void updateProfitLoss() {
        ReqUpdateProfitLoss reqUpdateProfitLoss = new ReqUpdateProfitLoss();
        reqUpdateProfitLoss.setZyzsId(mProfitLossInfo.getId());
        reqUpdateProfitLoss.setNum(num);
        reqUpdateProfitLoss.setOrderType(mOrderType);
        reqUpdateProfitLoss.setPlate("APP");
        reqUpdateProfitLoss.setPriceZy(profitPrice);
        reqUpdateProfitLoss.setStopProfit(profitMoney);
        reqUpdateProfitLoss.setPriceZs(lossPrice);
        reqUpdateProfitLoss.setStopLoss(lossMoney);
        if (!mIsOrdinary) {
            reqUpdateProfitLoss.setPriceZyRt(profitBackPrice);
            reqUpdateProfitLoss.setStopProfitRt(profitBackMoney);
            reqUpdateProfitLoss.setPriceZsRt(lossBackPrice);
            reqUpdateProfitLoss.setStopLossRt(lossBackMoney);
        }
        if (mOrderType == 2) {
            reqUpdateProfitLoss.setLimitPriceZy(profitWeituoPrice);
            reqUpdateProfitLoss.setLimitPriceZs(lossWeituoPrice);
            reqUpdateProfitLoss.setLimitPriceZyrt(profitBackWeituoPrice);
            reqUpdateProfitLoss.setLimitPriceZsrt(lossBackWeituoPrice);
        }
        showLoadingDialog();
        VolleyRequestUtils.getInstance().updateProfitLoss(this.toString(), reqUpdateProfitLoss, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                EventBusUtils.post(new EventMessage(EventCode.EVENT_PROFITLOSS_REFRESH));
                dismissLoadingDialog();
                showToast("修改成功");
                finish();
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
                dismissLoadingDialog();
                showToast(baseResponse.getMsg());
            }
        });
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_MARKET:
                HqMsg.YsHqInfo ysHqInfo = (HqMsg.YsHqInfo) event.getData();
                if (mPositionDetailsInfo.getVcContractCode().equals(ysHqInfo.getCommodityNo() + ysHqInfo.getContractNo1())) {
                    mCurrentPrice = NumberUtils.round(ysHqInfo.getQLastPrice(), count, ROUND_HALF_UP);
                    mTvPrice.setText(NumberUtils.roundStr(ysHqInfo.getQLastPrice(), count, ROUND_HALF_UP));
                }
                break;
            default:
                break;
        }
    }

}
